#include <assert.h>
#include <unistd.h>

#include <iostream>

using namespace std;

const static char* WORDS[] = {
    "contrive", "hum",          "imperil", "lade",   "addition",
    "blow",     "chance",       "mouth",   "pocket", "punishment",
    "rest",     "adjoining",    "alive",   "brown",  "feeble",
    "jolly",    "parsimonious", "sweet",   "tawdry", "verdant",
};

int main(int argc, char const* argv[]) {
  srand(time(NULL));
  /* [0 | 1]
   *  读  写 */
  int pipefd[2]{0};
  // 建立匿名管道
  int n = pipe(pipefd);
  assert(n == 0);
  (void)n;

  pid_t pid = fork();
  if (pid < 0) {
    perror("Error For fork");
    return 1;
  } else if (pid == 0) {
    // 子关读
    close(pipefd[0]);
    for (int i = 1; i <= 5; ++i) {
      char buff[128]{0};
      snprintf(buff, 128, "SUB[%d] -> %s", getpid(), WORDS[rand() % 20]);
      write(pipefd[1], buff, 128);
      sleep(1);
    }
    cout << "SUB FINISH" << endl;
    exit(0);
  }

  // 父关写
  close(pipefd[1]);
  char buff[128]{0};
  for (int i = 1; i <= 5; ++i) {
    ssize_t n = read(pipefd[0], buff, 128);
    if (n > 0) {
      cout << "MAIN[" << getpid() << "] <- " << buff << endl;
    } else if (n == 0) {
      break;
    }
    sleep(1);
  }
  cout << "MAIN FINISH" << endl;
  close(pipefd[0]);

  return 0;
}
